/**
 * 
 */
package cl.coretech.openbravo.translator.gui;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;

import net.miginfocom.swing.MigLayout;

import org.apache.log4j.Logger;

import cl.coretech.openbravo.translator.translation.Row;
import cl.coretech.openbravo.translator.translation.Translation;
import cl.coretech.openbravo.translator.translation.TranslationSerialization;
import cl.coretech.openbravo.translator.translation.Value;
import cl.coretech.openbravo.translator.ws.client.SvnWSClient;
import cl.coretech.util.ExtensionFileFilter;
import cl.coretech.util.FileUtils;
import cl.coretech.util.ResourceLoader;
import cl.coretech.util.TextAreaAppender;

// TODO: Auto-generated Javadoc
/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
/**
 * @author jsanta
 * 
 */
public class OpenbravoTranslatorGui extends JFrame {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -7679235327992134124L;

	/** The btn prev. */
	private JButton btnPrev = new JButton("");

	/** The btn next. */
	private JButton btnNext = new JButton("");

	/** The btn file. */
	private JButton btnFile = new JButton("...");

	/** The btn file ref. */
	private JButton btnFileRef = new JButton("...");
	// private JButton btnSave = new JButton("Guardar");
	/** The btn save. */
	private JButton btnSave = new JButton("Publicar");

	/** The btn copy. */
	private JButton btnCopy = new JButton("Copiar");

	/** The btn ok. */
	private JButton btnOK = new JButton("OK");

	/** The btn cancel. */
	private JButton btnCancel = new JButton("Cancelar");

	/** The lbl file. */
	private JLabel lblFile = new JLabel("Archivo");

	/** The lbl file ref. */
	private JLabel lblFileRef = new JLabel("Referencia");

	/** The lbl language. */
	private JLabel lblLanguage = new JLabel("Idioma");

	/** The lbl table. */
	private JLabel lblTable = new JLabel("Tabla");

	/** The lbl counter. */
	private JLabel lblCounter = new JLabel("");

	/** The lbl id. */
	private JLabel lblId = new JLabel("ID");

	/** The lbl original. */
	private JLabel lblOriginal = new JLabel("Original");

	/** The lbl translation. */
	private JLabel lblTranslation = new JLabel("Traducción");

	/** The lbl name. */
	private JLabel lblName = new JLabel("Nombre");

	/** The lbl description. */
	private JLabel lblDescription = new JLabel("Descripción");

	/** The lbl help. */
	private JLabel lblHelp = new JLabel("Ayuda");

	/** The lbl name ref. */
	private JLabel lblNameRef = new JLabel("Nombre");

	/** The lbl description ref. */
	private JLabel lblDescriptionRef = new JLabel("Descripción");

	/** The lbl help ref. */
	private JLabel lblHelpRef = new JLabel("Ayuda");

	/** The lbl ref file. */
	private JLabel lblRefFile = new JLabel("---");

	/** The fld file. */
	private JTextField fldFile = new JTextField();

	/** The fld file ref. */
	private JTextField fldFileRef = new JTextField();

	/** The fld language. */
	private JTextField fldLanguage = new JTextField();

	/** The fld table. */
	private JTextField fldTable = new JTextField();

	/** The fld id. */
	private JTextField fldId = new JTextField();

	/** The fld name orig. */
	private JTextField fldNameOrig = new JTextField();

	/** The fld description orig. */
	private JTextField fldDescriptionOrig = new JTextField();

	/** The fld help orig. */
	private JTextField fldHelpOrig = new JTextField();

	/** The fld name trans. */
	private JTextField fldNameTrans = new JTextField();

	/** The fld description trans. */
	private JTextField fldDescriptionTrans = new JTextField();

	/** The fld help trans. */
	private JTextField fldHelpTrans = new JTextField();

	/** The fld name orig ref. */
	private JTextField fldNameOrigRef = new JTextField();

	/** The fld description orig ref. */
	private JTextField fldDescriptionOrigRef = new JTextField();

	/** The fld help orig ref. */
	private JTextField fldHelpOrigRef = new JTextField();

	/** The fld name trans ref. */
	private JTextField fldNameTransRef = new JTextField();

	/** The fld description trans ref. */
	private JTextField fldDescriptionTransRef = new JTextField();

	/** The fld help trans ref. */
	private JTextField fldHelpTransRef = new JTextField();

	/** The chk auto ok. */
	private JCheckBox chkAutoOK = new JCheckBox("auto OK");

	/** The chk auto copy. */
	private JCheckBox chkAutoCopy = new JCheckBox("auto copiar");

	/** The txt info. */
	private JTextArea txtInfo = new JTextArea();

	/** The ref filename. */
	// private String refFilename = "---";
	/** The uploaded. */
	private boolean uploaded = false;

	private JMenuBar menu;
	// private JSeparator separador;

	private JMenu menuArchivo;
	private JMenuItem salir;

	/*private JMenu menuOpciones;
	private JMenuItem refreshConf;
	private JMenuItem preferences;*/

	private JMenu menuAyuda;
	private JMenuItem help;
	private JMenuItem license;
	private JMenuItem about;

	private Properties licenseProperties;
	private boolean licenseLoaded = false;

	/** The log. */
	private final Logger log = Logger.getLogger(this.getClass());

	/**
	 * Instantiates a new openbravo translator gui.
	 * 
	 * @throws ClassNotFoundException
	 *             the class not found exception
	 * @throws InstantiationException
	 *             the instantiation exception
	 * @throws IllegalAccessException
	 *             the illegal access exception
	 * @throws UnsupportedLookAndFeelException
	 *             the unsupported look and feel exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	public OpenbravoTranslatorGui() throws ClassNotFoundException,
			InstantiationException, IllegalAccessException,
			UnsupportedLookAndFeelException, IOException {
		// JFrame.setDefaultLookAndFeelDecorated(true);
		// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		initPanel();
		initMenu();
		setColors();

		this.setTitle("Coretech's OpenBravo ERP Translator");
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		this.pack();
		this.setSize(552, 779);

		this.setSize(550, this.getHeight());
		this.setLocationRelativeTo(null);
		this.setResizable(true);

		// Toolkit toolkit = Toolkit.getDefaultToolkit();
		// Dimension sz = toolkit.getScreenSize();
		this.setMinimumSize(this.getSize());
		// this.setMaximumSize(new Dimension((int)sz.getWidth(),
		// this.getHeight()));
		// this.setMaximizedBounds(new Rectangle(new
		// Dimension((int)sz.getWidth(), this.getHeight())));

		setAppender();

	}

	private void initMenu() throws IOException {

		menu = new JMenuBar();
		// separador = new JSeparator();

		setJMenuBar(menu);

		menuArchivo = new JMenu();
		menuArchivo.setText("Archivo");
		salir = new JMenuItem();
		salir.setText("Salir");

		menuArchivo.add(new JSeparator());
		menuArchivo.add(salir);
		salir.setIcon(new ImageIcon(ImageIO.read(ResourceLoader.loadResource(
				"cl/coretech/resources/exit24_h", ".png"))));
		menu.add(menuArchivo);

		menu.add(Box.createHorizontalGlue());

		menuAyuda = new JMenu();
		menuAyuda.setText("Ayuda");

		help = new JMenuItem();
		help.setText("Manual de usuario");

		license = new JMenuItem();
		license.setText("Cargar licencia");

		about = new JMenuItem();
		about.setText("Acerca de...");

		menuAyuda.add(help);
		help.setIcon(new ImageIcon(ImageIO.read(ResourceLoader.loadResource(
				"cl/coretech/resources/help24_h", ".png"))));
		
		menuAyuda.add(license);
		
		menuAyuda.add(new JSeparator());

		menuAyuda.add(about);
		about.setIcon(new ImageIcon(ImageIO.read(ResourceLoader.loadResource(
				"cl/coretech/resources/about24_h", ".png"))));

		menu.add(menuAyuda);

		setMenuListeners();

	}

	private void setMenuListeners() {

		salir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				salirActionPerformed(evt);
			}
		});

		help.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				helpActionPerformed(evt);
			}
		});
		license.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				licenseActionPerformed(evt);
			}
		});
		about.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				aboutActionPerformed(evt);
			}
		});

	}

	private void licenseActionPerformed(ActionEvent evt) {
		FileUtils fileUtils = new FileUtils();
		String licensePath = fileUtils.fileChoose(this,
				new ExtensionFileFilter("license"));

		if (licensePath != null) {
			if (!licensePath.trim().equals("")) {
				licenseProperties = new Properties();
				try {
					licenseProperties.load(new FileInputStream(licensePath));
					licenseLoaded = true;
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	private void salirActionPerformed(ActionEvent evt) {
		this.dispose();
		System.exit(1);
	}

	private void helpActionPerformed(ActionEvent evt) {
		ConversorLibrosHelp help = new ConversorLibrosHelp(this);
		help.setLocationRelativeTo(null);
		help.setVisible(true);
	}

	private void aboutActionPerformed(ActionEvent evt) {
		ConversorLibrosAbout about = new ConversorLibrosAbout(this);
		about.setLocationRelativeTo(null);
		about.setVisible(true);
	}

	/**
	 * Sets the colors.
	 */
	private void setColors() {
		// TODO Auto-generated method stub
		fldNameOrig.setEditable(false);
		// fldNameOrig.setEnabled(false);
		fldNameOrig.setBackground(new java.awt.Color(254, 254, 254));

		fldDescriptionOrig.setEditable(false);
		// fldDescriptionOrig.setEnabled(false);
		fldDescriptionOrig.setBackground(new java.awt.Color(254, 254, 254));

		fldHelpOrig.setEditable(false);
		// fldHelpOrig.setEnabled(false);
		fldHelpOrig.setBackground(new java.awt.Color(254, 254, 254));

		fldNameOrigRef.setEditable(false);
		// fldNameOrigRef.setEnabled(false);
		fldNameOrigRef.setBackground(new java.awt.Color(254, 254, 254));

		fldNameTransRef.setEditable(false);
		// fldNameTransRef.setEnabled(false);
		fldNameTransRef.setBackground(new java.awt.Color(254, 254, 254));

		fldDescriptionOrigRef.setEditable(false);
		// fldDescriptionOrigRef.setEnabled(false);
		fldDescriptionOrigRef.setBackground(new java.awt.Color(254, 254, 254));

		fldDescriptionTransRef.setEditable(false);
		// fldDescriptionTransRef.setEnabled(false);
		fldDescriptionTransRef.setBackground(new java.awt.Color(254, 254, 254));

		fldHelpOrigRef.setEnabled(false);
		// fldHelpOrigRef.setEditable(false);
		fldHelpOrigRef.setBackground(new java.awt.Color(254, 254, 254));

		fldHelpTransRef.setEnabled(false);
		// fldHelpTransRef.setEditable(false);
		fldHelpTransRef.setBackground(new java.awt.Color(254, 254, 254));
	}

	/**
	 * Sets the appender.
	 */
	private void setAppender() {
		TextAreaAppender.setTextArea(txtInfo);
	}

	/**
	 * Inits the panel.
	 * 
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	private void initPanel() throws IOException {
		MigLayout layout = new MigLayout("fillx, filly",
				"[110!][50%-66!][50%-66!]");

		this.setLayout(layout);

		this.add(lblFile, "");
		this.add(fldFile, "split 2, growx");
		fldFile.setEditable(false);
		fldFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				fldFileActionPerformed(evt);
			}
		});
		this.add(btnFile, "");
		btnFile.setIcon(new ImageIcon(ImageIO.read(ResourceLoader.loadResource(
				"cl/coretech/resources/folder_closed", ".png"))));
		btnFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				btnFileActionPerformed(evt);
			}
		});

		// this.add(btnSave, "grow 100, wrap");
		this.add(btnSave, "growx, growy 4, spany 4, wrap");
		btnSave.setIcon(new ImageIcon(ImageIO.read(ResourceLoader.loadResource(
				"cl/coretech/resources/upload_arrow", ".png"))));
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				try {
					btnSaveActionPerformed(evt);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		this.add(lblFileRef, "");
		this.add(fldFileRef, "split 2, growx");
		fldFileRef.setEditable(false);
		fldFileRef.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				fldFileRefActionPerformed(evt);
			}
		});
		this.add(btnFileRef, "wrap");
		btnFileRef.setIcon(new ImageIcon(ImageIO.read(ResourceLoader
				.loadResource("cl/coretech/resources/folder_closed", ".png"))));
		btnFileRef.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				btnFileRefActionPerformed(evt);
			}
		});

		this.add(lblLanguage, "");
		this.add(fldLanguage, "wmin 200px, growx, wrap");
		fldLanguage.setEditable(false);
		fldLanguage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				fldLanguageActionPerformed(evt);
			}
		});

		this.add(lblTable, "");
		this.add(fldTable, "wmin 200px, growx, wrap");
		fldTable.setEditable(false);
		fldTable.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				fldTableActionPerformed(evt);
			}
		});

		/* Referencia */
		this.add(new JSeparator(),
				"span 3, gaptop 15px,, gapbottom 15px, growx, wrap");
		this.add(new JLabel("Referencia cargada de: "), "span, split 2");
		this.add(lblRefFile, "wrap");

		this.add(new JLabel("Original"), "skip 1, align center");
		this.add(new JLabel("Traducción"), "align center, wrap");

		this.add(lblNameRef, "");
		this.add(fldNameOrigRef, "wmin 200px, growx");
		this.add(fldNameTransRef, "wmin 200px, growx, wrap");

		this.add(lblDescriptionRef, "");
		this.add(fldDescriptionOrigRef, "wmin 200px, growx");
		this.add(fldDescriptionTransRef, "wmin 200px, growx, wrap");

		this.add(lblHelpRef, "");
		this.add(fldHelpOrigRef, "wmin 200px, growx");
		this.add(fldHelpTransRef, "wmin 200px, growx, wrap");
		this.add(chkAutoCopy, "span, split 2, align right");
		this.add(btnCopy);
		btnCopy.setIcon(new ImageIcon(ImageIO.read(ResourceLoader.loadResource(
				"cl/coretech/resources/copy_two_documents", ".png"))));
		btnCopy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				btnCopyActionPerformed(evt);
			}
		});
		/* Fin Referencia */

		this.add(new JSeparator(), "span 3, gaptop 15px, growx, wrap");

		this.add(lblCounter, "gaptop 15px, split 3, span, align right");
		this.add(btnPrev, "gaptop 15px");
		btnPrev.setIcon(new ImageIcon(ImageIO.read(ResourceLoader.loadResource(
				"cl/coretech/resources/arrow_left_triangle", ".png"))));
		btnPrev.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				btnPrevActionPerformed(evt);
			}
		});
		this.add(btnNext, "gaptop 15px, wrap");
		btnNext.setIcon(new ImageIcon(ImageIO.read(ResourceLoader.loadResource(
				"cl/coretech/resources/arrow_right_triangle", ".png"))));
		btnNext.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				btnNextActionPerformed(evt);
			}
		});

		this.add(lblId, "split 2, span, gapright 15px");
		this.add(fldId, "wmin 150px, wrap");
		fldId.setEditable(false);
		fldId.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				fldIdActionPerformed(evt);
			}
		});

		this.add(lblOriginal, "skip 1, align center");
		this.add(lblTranslation, "align center, wrap");

		this.add(lblName, "");
		this.add(fldNameOrig, "wmin 200px, growx");
		fldNameOrig.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				fldNameOrigActionPerformed(evt);
			}
		});
		this.add(fldNameTrans, "wmin 200px, growx, wrap");
		fldNameTrans.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				fldNameTransActionPerformed(evt);
			}
		});

		this.add(lblDescription, "");
		this.add(fldDescriptionOrig, "wmin 200px, growx");
		fldDescriptionOrig.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				fldDescriptionOrigActionPerformed(evt);
			}
		});
		this.add(fldDescriptionTrans, "wmin 200px, growx, wrap");
		fldDescriptionTrans.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				fldDescriptionTransActionPerformed(evt);
			}
		});

		this.add(lblHelp, "");
		this.add(fldHelpOrig, "wmin 200px, growx");
		fldHelpOrig.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				fldHelpOrigActionPerformed(evt);
			}
		});
		this.add(fldHelpTrans, "wmin 200px, growx, wrap");
		fldHelpTrans.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				fldHelpTransActionPerformed(evt);
			}
		});

		this.add(chkAutoOK, "span, split 3, align right");
		this.add(btnCancel, "wmin 90px");
		btnCancel.setIcon(new ImageIcon(ImageIO
				.read(ResourceLoader.loadResource(
						"cl/coretech/resources/close_stop_wrong", ".png"))));
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				btnCancelActionPerformed(evt);
			}
		});
		this.add(btnOK, "wmin 90px");
		btnOK.setIcon(new ImageIcon(ImageIO.read(ResourceLoader.loadResource(
				"cl/coretech/resources/right", ".png"))));
		btnOK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				btnOKActionPerformed(evt);
			}
		});

		txtInfo.setColumns(30);
		txtInfo.setRows(15);
		txtInfo.setAutoscrolls(true);
		txtInfo.setDoubleBuffered(true);
		JScrollPane txtScrollPane = new JScrollPane(txtInfo);
		this
				.add(txtScrollPane,
						"gaptop 15px, span, align center, growx, growy");
		txtScrollPane.setViewportView(txtInfo);
		txtInfo.setEditable(false);

		this.btnFileRef.setEnabled(false);

	}

	/**
	 * Btn copy action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	protected void btnCopyActionPerformed(ActionEvent evt) {
		String name = fldNameTransRef.getText();
		String desc = fldDescriptionTransRef.getText();
		String help = fldHelpTransRef.getText();

		fldNameTrans.setText(name);
		fldDescriptionTrans.setText(desc);
		fldHelpTrans.setText(help);

	}

	/**
	 * Btn file ref action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	protected void btnFileRefActionPerformed(ActionEvent evt) {

		FileUtils fileUtils = new FileUtils();
		String workFilePath = fileUtils.fileChoose(this,
				new ExtensionFileFilter("xml"));
		this.fldFileRef.setText(workFilePath);
		File workFile = new File(workFilePath);
		try {
			if (workFile.exists()) {

				TranslationSerialization serialization = new TranslationSerialization(
						workFilePath);
				translationRef = serialization.deSerialize();
				// this.fldLanguage.setText(translation.getLanguage());
				String workTable = this.fldTable.getText();
				if (!workTable.equalsIgnoreCase(translationRef.getTable())) {
					log
							.error("La tabla del archivo de referencia no corresponde a la tabla de trabajo: "
									+ workTable
									+ " != "
									+ translationRef.getTable());
				} else {
					this.rowsRef = translationRef.getRows();
					loadRefRecord(0);
					lblRefFile.setText(workFilePath);
				}
			} else {
				log.error("No existe el archivo");
			}

		} catch (Exception e) {
			log.error("No fue posible deserializar el archivo " + workFilePath
					+ ". Probablemente no contiene registros para traducir.");
			e.printStackTrace();
		}

	}

	/**
	 * Fld file ref action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	protected void fldFileRefActionPerformed(ActionEvent evt) {
		// TODO Auto-generated method stub

	}

	/**
	 * The main method.
	 * 
	 * @param args
	 *            the args
	 */
	public static void main(String[] args) {
		// JFrame.setDefaultLookAndFeelDecorated(true);

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				OpenbravoTranslatorGui translatorGui;
				try {
					translatorGui = new OpenbravoTranslatorGui();
					translatorGui.setVisible(true);
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (UnsupportedLookAndFeelException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

	}

	/** The current index. */
	private int currentIndex = -1;

	/** The translation. */
	private Translation translation;

	/** The rows. */
	private List<Row> rows;

	/** The translation ref. */
	private Translation translationRef;

	/** The rows ref. */
	private List<Row> rowsRef;

	/**
	 * Fld file action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void fldFileActionPerformed(ActionEvent evt) {
	}

	/**
	 * Clear gui.
	 */
	private void clearGui() {
		this.translation = null;
		this.fldFile.setText("");
		this.translationRef = null;
		this.fldFileRef.setText("");
		this.fldLanguage.setText("");
		this.fldTable.setText("");

		this.lblName.setText("");
		this.fldNameOrig.setText("");
		this.fldNameTrans.setText("");

		this.lblDescription.setText("");
		this.fldDescriptionOrig.setText("");
		this.fldDescriptionTrans.setText("");

		this.lblHelp.setText("");
		this.fldHelpOrig.setText("");
		this.fldHelpTrans.setText("");

		this.lblNameRef.setText("");
		this.fldNameOrigRef.setText("");
		this.fldNameTransRef.setText("");

		this.lblDescriptionRef.setText("");
		this.fldDescriptionOrigRef.setText("");
		this.fldDescriptionTransRef.setText("");

		this.lblHelpRef.setText("");
		this.fldHelpOrigRef.setText("");
		this.fldHelpTransRef.setText("");

		this.lblCounter.setText("");

		this.btnFileRef.setEnabled(false);
	}

	/**
	 * Load record.
	 * 
	 * @param index
	 *            the index
	 */
	private void loadRecord(int index) {
		if (rows != null && rows.size() > 0) {
			this.currentIndex = index;
			this.lblCounter.setText("Registro " + (index + 1) + " de "
					+ this.rows.size());
			Row row = rows.get(index);

			this.fldId.setText("" + row.getId());

			List<Value> values = row.getValues();

			this.lblName.setText(values.get(0).getColumn());
			this.fldNameOrig.setText(values.get(0).getOriginal());
			this.fldNameTrans.setText(values.get(0).getValue());

			this.lblDescription.setText(values.get(1).getColumn());
			this.fldDescriptionOrig.setText(values.get(1).getOriginal());
			this.fldDescriptionTrans.setText(values.get(1).getValue());

			if (values.size() >= 3) {
				this.lblHelp.setText(values.get(2).getColumn());
				this.fldHelpOrig.setText(values.get(2).getOriginal());
				this.fldHelpTrans.setText(values.get(2).getOriginal());

				this.fldHelpTrans.setEnabled(true);
			} else {
				this.lblHelp.setText("");
				this.fldHelpOrig.setText("");
				this.fldHelpTrans.setText("");

				this.fldHelpOrig.setEnabled(false);
				this.fldHelpTrans.setEnabled(false);
			}

			if (values.size() > 3) {
				log.info("Hay un total" + values.size());
			}
		} else {
			log.warn("Procure cargar un archivo");
		}

	}

	/**
	 * Load ref record.
	 * 
	 * @param index
	 *            the index
	 */
	private void loadRefRecord(int index) {
		if (rowsRef != null && rowsRef.size() > 0) {
			Row row = rowsRef.get(index);
			List<Value> values = row.getValues();

			this.lblNameRef.setText(values.get(0).getColumn());
			this.fldNameOrigRef.setText(values.get(0).getOriginal());
			this.fldNameTransRef.setText(values.get(0).getValue());

			this.lblDescriptionRef.setText(values.get(1).getColumn());
			this.fldDescriptionOrigRef.setText(values.get(1).getOriginal());
			this.fldDescriptionTransRef.setText(values.get(1).getValue());

			if (values.size() >= 3) {
				this.lblHelpRef.setText(values.get(2).getColumn());
				this.fldHelpOrigRef.setText(values.get(2).getOriginal());
				this.fldHelpTransRef.setText(values.get(2).getOriginal());
			} else {
				this.lblHelpRef.setText("");
				this.fldHelpOrigRef.setText("");
				this.fldHelpTransRef.setText("");

				this.fldHelpOrigRef.setEnabled(false);
				this.fldHelpTransRef.setEnabled(false);
			}

			if (values.size() > 3) {
				log.info("Hay un total" + values.size());
			}
		} else {
			log.warn("Procure cargar un archivo de referencia");
		}

	}

	/**
	 * Btn save action performed.
	 * 
	 * @param evt
	 *            the evt
	 * 
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	private void btnSaveActionPerformed(ActionEvent evt) throws IOException {
		String workFilePath = this.fldFile.getText();
		String wsResponse = "ERROR";
		TranslationSerialization serialization = new TranslationSerialization(
				workFilePath);

		if (!uploaded) {
			try {
				if (licenseLoaded) {
					byte[] data = serialization.serializeBytes(translation);

					SvnWSClient svnWSClient = new SvnWSClient(data,
							licenseProperties, workFilePath);
					wsResponse = svnWSClient.uploadFile();
					log.info("WS responde: " + wsResponse);
				} else {
					log.error("Recuerde cargar el archivo de propiedades");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (wsResponse.equalsIgnoreCase("OK")) {
				btnSave.setText("Guardar");
				btnSave
						.setIcon(new ImageIcon(ImageIO.read(ResourceLoader
								.loadResource("cl/coretech/resources/floppy",
										".png"))));

				uploaded = true;
			} else {
				log.error("No se pudo publicar el archivo.");
			}
		} else {
			try {
				serialization.serialize(translation);
				log.info("Archivo " + workFilePath + " almacenado");

				uploaded = false;
				btnSave.setText("Publicar");
				btnSave.setIcon(new ImageIcon(ImageIO.read(ResourceLoader
						.loadResource("cl/coretech/resources/upload_arrow",
								".png"))));
			} catch (Exception e) {
				log.error("No se pudo almacenar el archivo " + workFilePath);
				e.printStackTrace();
			}
		}
	}

	/**
	 * Btn file action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void btnFileActionPerformed(ActionEvent evt) {
		FileUtils fileUtils = new FileUtils();
		String workFilePath = fileUtils.fileChoose(this,
				new ExtensionFileFilter("xml"));
		this.fldFile.setText(workFilePath);
		File workFile = new File(workFilePath);
		try {
			if (workFile.exists()) {

				TranslationSerialization serialization = new TranslationSerialization(
						workFilePath);
				translation = serialization.deSerialize();
				this.fldLanguage.setText(translation.getLanguage());
				this.fldTable.setText(translation.getTable());

				this.rows = translation.getRows();
				loadRecord(0);
				log.info("Archivo " + workFilePath + " cargado");

				this.btnFileRef.setEnabled(true);
			} else {
				log.error("No existe el archivo");
				clearGui();
			}

		} catch (Exception e) {
			log.error("No se pudo deserializar el archivo " + workFilePath);
		}
	}

	/**
	 * Fld language action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void fldLanguageActionPerformed(ActionEvent evt) {
		System.out.println("fldLanguage.actionPerformed, event=" + evt);
		// TODO add your code for fldLanguage.actionPerformed
	}

	/**
	 * Fld table action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void fldTableActionPerformed(ActionEvent evt) {
		System.out.println("fldTable.actionPerformed, event=" + evt);
		// TODO add your code for fldTable.actionPerformed
	}

	/**
	 * Fld id action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void fldIdActionPerformed(ActionEvent evt) {
		System.out.println("fldId.actionPerformed, event=" + evt);
		// TODO add your code for fldId.actionPerformed
	}

	/**
	 * Fld name orig action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void fldNameOrigActionPerformed(ActionEvent evt) {
		System.out.println("fldNameOrig.actionPerformed, event=" + evt);
		// TODO add your code for fldNameOrig.actionPerformed
	}

	/**
	 * Fld name trans action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void fldNameTransActionPerformed(ActionEvent evt) {
		System.out.println("fldNameTrans.actionPerformed, event=" + evt);
		// TODO add your code for fldNameTrans.actionPerformed
	}

	/**
	 * Fld description orig action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void fldDescriptionOrigActionPerformed(ActionEvent evt) {
		System.out.println("fldDescriptionOrig.actionPerformed, event=" + evt);
		// TODO add your code for fldDescriptionOrig.actionPerformed
	}

	/**
	 * Fld description trans action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void fldDescriptionTransActionPerformed(ActionEvent evt) {
		System.out.println("fldDescriptionTrans.actionPerformed, event=" + evt);
		// TODO add your code for fldDescriptionTrans.actionPerformed
	}

	/**
	 * Fld help orig action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void fldHelpOrigActionPerformed(ActionEvent evt) {
		System.out.println("fldHelpOrig.actionPerformed, event=" + evt);
		// TODO add your code for fldHelpOrig.actionPerformed
	}

	/**
	 * Fld help trans action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void fldHelpTransActionPerformed(ActionEvent evt) {
		System.out.println("fldHelpTrans.actionPerformed, event=" + evt);
		// TODO add your code for fldHelpTrans.actionPerformed
	}

	/**
	 * Btn cancel action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void btnCancelActionPerformed(ActionEvent evt) {
		loadRecord(currentIndex);
	}

	/**
	 * Btn ok action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void btnOKActionPerformed(ActionEvent evt) {
		List<Value> values = new ArrayList<Value>();

		String column = this.lblName.getText();
		String original = this.fldNameOrig.getText();
		String val = this.fldNameTrans.getText();
		Value nameVal = new Value(column, original, val);
		values.add(nameVal);
		if (log.isDebugEnabled()) {
			log.debug("Datos[1]: " + column + ", " + original + ", " + val);
		}

		column = this.lblDescription.getText();
		original = this.fldDescriptionOrig.getText();
		val = this.fldDescriptionTrans.getText();
		Value descVal = new Value(column, original, val);
		values.add(descVal);
		if (log.isDebugEnabled()) {
			log.debug("Datos[2]: " + column + ", " + original + ", " + val);
		}

		column = this.lblHelp.getText();
		if (!column.equals("")) {
			original = this.fldHelpOrig.getText();
			val = this.fldHelpTrans.getText();
			Value helpVal = new Value(column, original, val);
			values.add(helpVal);
			if (log.isDebugEnabled()) {
				log.debug("Datos[3]: " + column + ", " + original + ", " + val);
			}
		}

		int id = Integer.parseInt(this.fldId.getText());
		String trl = "N";
		Row row = new Row(id, trl, values);

		rows.set(currentIndex, row);

	}

	/**
	 * Btn prev action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void btnPrevActionPerformed(ActionEvent evt) {
		if (chkAutoOK.isSelected()) {
			btnOKActionPerformed(evt);
			if (log.isDebugEnabled()) {
				log.debug("Actualizando datos");
			}
		}

		if (rows != null && this.currentIndex - 1 >= 0) {
			int idx = this.currentIndex - 1;
			loadRecord(idx);
			loadRefRecord(idx);

			if (chkAutoCopy.isSelected()) {
				btnCopyActionPerformed(evt);
				if (log.isDebugEnabled()) {
					log.debug("Copiando datos");
				}
			}
		} else {
			System.out.println("No puedo retroceder");
			if (rows == null)
				System.out.println("Asegurese de cargar un archivo");
		}
	}

	/**
	 * Btn next action performed.
	 * 
	 * @param evt
	 *            the evt
	 */
	private void btnNextActionPerformed(ActionEvent evt) {
		if (chkAutoOK.isSelected()) {
			btnOKActionPerformed(evt);
			if (log.isDebugEnabled()) {
				log.debug("Actualizando datos");
			}
		}
		if (rows != null && this.currentIndex + 1 < rows.size()) {
			int idx = this.currentIndex + 1;
			loadRecord(idx);
			loadRefRecord(idx);

			if (chkAutoCopy.isSelected()) {
				btnCopyActionPerformed(evt);
				if (log.isDebugEnabled()) {
					log.debug("Copiando datos");
				}
			}
		} else {
			System.out.println("No puedo avanzar");
			if (rows == null)
				System.out.println("Asegurese de cargar un archivo");
		}
	}

}
